package com.micro.ai.template.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;

/**
 * Spring Security 配置
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true)
public class SecurityConfig {

    /**
     * 配置Security过滤链
     * 
     * 注意：本服务通过Gateway统一鉴权，因此只需要验证从Gateway传递过来的用户信息
     * Gateway会在请求头中注入 X-User-Id 和 X-Tenant-Id
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            // 禁用CSRF（使用JWT，无需CSRF保护）
            .csrf(AbstractHttpConfigurer::disable)
            
            // 禁用CORS（由Gateway处理）
            .cors(AbstractHttpConfigurer::disable)
            
            // 禁用表单登录
            .formLogin(AbstractHttpConfigurer::disable)
            
            // 禁用HTTP Basic认证
            .httpBasic(AbstractHttpConfigurer::disable)
            
            // 禁用默认登出
            .logout(AbstractHttpConfigurer::disable)
            
            // 会话管理：无状态
            .sessionManagement(session -> 
                session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            )
            
            // 授权配置
            .authorizeHttpRequests(auth -> auth
                // 健康检查和监控端点公开访问
                .requestMatchers("/actuator/**").permitAll()
                
                // Knife4j文档公开访问（生产环境建议关闭或限制IP）
                .requestMatchers("/doc.html", "/webjars/**", "/v3/api-docs/**", "/swagger-resources/**").permitAll()
                
                // Nacos配置刷新端点
                .requestMatchers("/actuator/refresh").permitAll()
                
                // 其他所有请求都需要认证（由Gateway负责）
                .anyRequest().authenticated()
            );
        
        return http.build();
    }
}
